<?php
require_once('db.inc.php');

class type_transaction {
	var $id;
	var $libelle;
	var $tableName = 'type_transaction';

	function type_transaction($id=0)
	{
		$this->id = $id;
		if ($this->id != 0) {
			$rs = sql_query("SELECT libelle FROM " . $this->tableName . " WHERE id=" . $this->id);
			$this->libelle = htmlentities(stripslashes($rs->fields['libelle']));
		}
	}
	
	function reload()
	{
		$this->type_transaction($this->id);
	}
	
	function delete()
	{
		sql_query("DELETE FROM " . $this->tableName . " WHERE id=" . $this->id);
	}

	function save()
	{
		global $conn;
		if ($this->id == 0)
		{
		    $sql = "INSERT INTO " . $this->tableName . " (libelle) VALUES ('" . addslashes($this->libelle) . "')";
		}
		else
		{
			$sql = "UPDATE " . $this->tableName . " SET libelle='" . addslashes($this->libelle) . "' WHERE id=" . $this->id . " LIMIT 1";
		}
		if ($conn->Execute($sql) === false) {
		     if ($conn->ErrorNo() == 1062)
                 return ERROR_1062;
             else {
                 log_error("Erreur MySQL dans la SAUVEGARDE de " . $this->tableName . " > " . $sql);
                 return ERROR_MYSQL;
             }
        }
        $this->id = $conn->Insert_ID();
        return true;
	}

	function getLibelle($id)
	{
		$rs = sql_query("SELECT libelle FROM " . $this->tableName . " WHERE id=" . $id);
		return htmlentities($rs->fields['libelle']);
	}
	
	function getDefaultLibelle()
	{
    	return $this->getLibelle('1');
	}
	
	function getAll()
	{
		$data = array();
		$data[1]['libelle'] = $this->getDefaultLibelle();
		$recordSet = sql_query("SELECT * FROM " . $this->tableName . " WHERE id<>1 ORDER BY libelle ASC");
		while (!$recordSet->EOF) {
			$id = $recordSet->fields['id'];
			$data[$id]['libelle'] = htmlentities($recordSet->fields['libelle']);
			$recordSet->MoveNext();
		}
		return $data;
	}

    // renvoi le code html pour un element formulaire de type select + son label
	function getSelect($selectedId=false)
	{
	    $label = '<label for="type_transaction_id">Type de transaction</label>';
        $select = '<select id="type_transaction_id" name="type_transaction_id">';
        foreach ($this->getAll() as $id => $tab) {
            $select.= '<option value="' . $id . '"';
            if($selectedId!==false && $selectedId==$id) $select.= ' selected="selected"';
            $select.= '>' . $tab['libelle'] . '</option>';
        }
        $select.= '</select>';
        $html = $label . $select;
        return $html;
	}

}
